import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:provider/provider.dart';
import 'package:yhdm_mobile/page/home/home_entity.dart';
import 'package:yhdm_mobile/page/home/search_delegate.dart';
import 'package:yhdm_mobile/utils/route_utils.dart';
import 'package:yhdm_mobile/utils/iterable_ex.dart';

import 'home/home_view_model.dart';

class HomePage extends StatelessWidget {
  final PageController pageController = PageController(initialPage: 0);
  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    var viewModel = HomeViewModel(context);
    return ChangeNotifierProvider<HomeEntity>.value(
      value: viewModel.entity,
      builder: (BuildContext context, child) {
        return Scaffold(
          body: CustomScrollView(
            slivers: [
              SliverAppBar(
                title: Text('樱花动漫'),
                actions: [
                  IconButton(
                    icon: Icon(Icons.search),
                    onPressed: () {
                      showSearch(
                          context: context, delegate: AnimSearchDelegate());
                    },
                  ),
                ],
              ),
              SliverList(
                  delegate: SliverChildListDelegate([
                Container(
                  margin: EdgeInsets.symmetric(vertical: 10),
                  padding: EdgeInsets.symmetric(horizontal: 5),
                  height: size.width * .6,
                  child: PageView(
                    physics: BouncingScrollPhysics(),
                    controller: pageController,
                    children: [
                      ...buildBanner(context),
                    ],
                  ),
                ),
                ...buildClassList(context),
              ])),
            ],
          ),
        );
      },
    );
  }

  List<Widget> buildBanner(BuildContext context) {
    var homeEntity = context.watch<HomeEntity>();
    var bannerList = List<Widget>();

    homeEntity.bannerList?.forEachAsIndex((element, index) {
      bannerList.add(
        AnimatedBuilder(
            animation: pageController,
            builder: (context, child) {
              double value;
              if (pageController.position.haveDimensions) {
                value = pageController.page - index;
              }
              return BannerImageWidget(
                imageUrl: element.imageUrl,
                url: element.url,
                name: element.name,
              );
            }),
      );
    });
    return bannerList;
  }
}

class AnimeCardWidget extends StatelessWidget {
  final String imageUrl;
  final GestureTapCallback onImageTap;
  final GestureTapCallback onNameTap;
  final String name;
  final String episode;
  const AnimeCardWidget(
      {Key key,
      this.imageUrl,
      this.onImageTap,
      this.name,
      this.onNameTap,
      this.episode})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    return Container(
      width: (size.width - 30) * 1 / 3,
      child: Column(
        children: [
          GestureDetector(
            onTap: onImageTap,
            child: Container(
              height: size.width * 3 / 6,
              child: Card(
                elevation: 3,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(5),
                  child: Stack(
                    fit: StackFit.expand,
                    children: [
                      Image.network(
                        imageUrl,
                        fit: BoxFit.cover,
                      ),
                      Positioned(
                        left: 0,
                        right: 0,
                        bottom: 0,
                        child: Container(
                          height: 20,
                          alignment: Alignment.centerLeft,
                          padding: EdgeInsets.symmetric(horizontal: 5),
                          color: Colors.black45,
                          child: Text(
                            episode,
                            style: TextStyle(color: Colors.white, fontSize: 11),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
          GestureDetector(
            child: Text(name),
            onTap: onNameTap,
          ),
        ],
      ),
    );
  }
}

List<Widget> buildClassList(BuildContext context) {
  var size = MediaQuery.of(context).size;
  var list = List<Widget>();
  var homeEntity = context.watch<HomeEntity>();
  homeEntity.classList?.forEach((element) {
    var title = Container(
      width: size.width,
      padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      child: Row(
        children: [
          Text(
            element.className,
            style: Theme.of(context)
                .textTheme
                .subtitle1
                .copyWith(color: Colors.black, fontWeight: FontWeight.bold),
          ),
          Expanded(child: SizedBox.shrink()),
          Text(
            '查看更多',
            style: Theme.of(context).textTheme.bodyText2,
          ),
          Icon(
            Icons.keyboard_arrow_right,
            size: 22,
            color: Theme.of(context).textTheme.bodyText2.color,
          ),
        ],
      ),
    );
    var cards = Container(
      padding: EdgeInsets.all(10),
      child: Wrap(
        spacing: 5,
        runSpacing: 5,
        children: [
          ...buildCardList(context, element.animeList),
        ],
      ),
    );
    list.add(title);
    list.add(cards);
  });

  return list;
}

List<Widget> buildCardList(BuildContext context, List<AnimeEntity> classList) {
  var list = List<Widget>();
  classList.forEach((element) {
    list.add(AnimeCardWidget(
      name: element.name,
      imageUrl: element.imageUrl,
      episode: element.episode,
      onImageTap: () {
        RouteUtils.openPage(context, element.url, element.name);
      },
      onNameTap: () {
        RouteUtils.openPage(context, element.url, element.name);
      },
    ));
  });
  return list;
}

class BannerImageWidget extends StatelessWidget {
  final String imageUrl;
  final String url;
  final String name;

  const BannerImageWidget({Key key, this.imageUrl, this.url, this.name})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        RouteUtils.openPage(context, url, name);
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 5),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(5),
          child: CachedNetworkImage(imageUrl: imageUrl, fit: BoxFit.cover),
        ),
      ),
    );
  }
}
